﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace Extensions
{
    /// <summary>
    /// Extension methods class
    /// </summary>
    public static class ExtensionsUtil
    {
        /// <summary>
        /// Get the string slice between the two indexes.
        /// Inclusive for start index, exclusive for end index.
        /// </summary>
        public static string Slice(this string source, int start, int end)
        {
            if (end < 0) // Keep this for negative end support
            {
                end = source.Length + end;
            }

            int len = end - start;               // Calculate length
            return source.Substring(start, len); // Return Substring of length
        }

        /// <summary>
        /// Truncate string on whole words
        /// </summary>
        public static string TruncateAtWord(this string input, int length, bool stripHtmlTags = false)
        {
            if (input == null || input.Length < length)
            {
                return input;
            }

            input = input.Trim();

            if (stripHtmlTags)
            {
                //input = Regex.Replace(input, @"<(.|\n)*?>", string.Empty);
                input = Regex.Replace(input, @"<.*?>", string.Empty);
            }

            int lastSpaceIndex = input.LastIndexOf(" ", length); // Get last space index
            while ((lastSpaceIndex + 3) > length)
            {
                lastSpaceIndex = input.Substring(0, lastSpaceIndex).Trim().LastIndexOf(" ");
            }

            return String.Format("{0}...", input.Substring(0, (lastSpaceIndex > 0) ? lastSpaceIndex : length - 3).Trim()); // Return Substring of length
        }
    }
}
